﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Product App</title>
</head>
<body>
    <div>
        <h2>All Products</h2>
        <ul id="products" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <input type="button" value="Show All" onclick="showAll();" />
        <p id="message" />
    </div>
    <hr />
    <p><a href="/wwwroot/url-test.html" target="_blank">跳转到Product Controller URL测试页</a></p>
    <p><a href="/Help/Index" target="_blank">跳转到 API 帮助页</a></p>
    <script>
        var uri = '/api/product';
        function showAll() {
            document.querySelector('#products').innerHTML = "";
            fetch(uri).then(res => res.json())
                .then(data => {
                    data.forEach(item => {
                        // Add a list item for the product.
                        var li = document.createElement('li');
                        li.innerText = formatItem(item);
                        document.querySelector('#products').appendChild(li);
                    });
                })
        }
        function formatItem(item) {
            return "id:" + item.Id + " - " + item.Name + ': $' + item.Price;
        }

        function find() {
            var id = document.querySelector('#prodId').value;
            var url = uri;
            if (id !== "") {
                url = uri + '/' + id;
            } else {
                document.querySelector('#message').innerText = 'please enter the id';
                return;
            }
            fetch(url).then(res => {
                if (res.ok) {
                    return res.json()
                } else {
                    throw new Error('Not Found');
                }
            })
                .then(function (data) {
                    document.querySelector('#message').innerText = formatItem(data);
                }).catch(err => {
                    document.querySelector('#message').innerText = 'Error: ' + err.message;
                });
        }
        showAll();
    </script>
</body>
</html>